package com.lalosoft.gastostarjetaweb.servlet;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lalosoft.gastostarjetaweb.Constants;
import com.lalosoft.gastostarjetaweb.dao.EmailDao;
import com.lalosoft.gastostarjetaweb.dao.ItemDao;
import com.lalosoft.gastostarjetaweb.dao.UserDao;
import com.lalosoft.gastostarjetaweb.model.Email;
import com.lalosoft.gastostarjetaweb.model.Item;
import com.lalosoft.gastostarjetaweb.model.User;
import com.lalosoft.gastostarjetaweb.pmf.PMF;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger("LoginServlet");
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String email = req.getParameter("email");
		String password = req.getParameter("password");
		
		if(email.equals("admin@gastostarjeta.appspotmail.com") && 
				password.equals("admin")){
			log.log(Level.WARNING, "usuario admin");
			List<Email> list = EmailDao.findByState(Constants.ESTADO_RECIBIDO);
			req.setAttribute("emails", list);
		    RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/inbox.jsp");
		    requestDispatcher.forward(req, resp);
		} else {
			User user = UserDao.getUser(email, password);
			if(user != null){
				PersistenceManager pm = PMF.get().getPersistenceManager();
				List<Item> items = null;
				try{
					items = ItemDao.findByToken(user.getUuid(), pm);
				} finally {
					pm.close();
				}
				log.log(Level.WARNING, "Usuario existe! ");
				req.setAttribute("user", user);
				req.setAttribute("items", items);
		        RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/index.jsp");
		        requestDispatcher.forward(req, resp);
			} else {
				log.log(Level.WARNING, "Usuario NO existe");
				RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/error.html");
		        requestDispatcher.forward(req, resp);
			}
		}
		
		
	}

}
